import 'dart:async';
import 'dart:io';

import 'package:camera/camera.dart';
import 'package:flutter/material.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart';
import 'package:get/get.dart';
import 'package:kkhousekeep/page/public/take_picture_screen_controller.dart';
import 'package:kkhousekeep/tools/log.dart';
import 'package:local_image_provider/local_image_provider.dart';

import '../../models/pick_picture.dart';
import '../../widget/custom_button.dart';

typedef PhotoPathCallBack<T extends PickPictureModel> = Function(T t);

/// 传入controller的可观察图片列表即可
class TakePictureScreen extends StatefulWidget {
  final List<String>? imagePathList;
  final PhotoPathCallBack? photoPathCallBack;
  final bool uerGallery;

  const TakePictureScreen({
    super.key,
    this.imagePathList,
    this.photoPathCallBack,
    this.uerGallery = false,
  }) : assert(imagePathList != null || photoPathCallBack != null);

  @override
  State<StatefulWidget> createState() => _TakePictureScreenState();
}

class _TakePictureScreenState extends State<TakePictureScreen>
    with WidgetsBindingObserver {

  @override
  void initState() {
    super.initState();
    WidgetsBinding.instance.addObserver(this);
  }

  @override
  void dispose() {
    WidgetsBinding.instance.removeObserver(this);
    logI("take picture screen dispose");
    super.dispose();
  }

  ///App在后台运行释放相机控制器，恢复时重新创建
  @override
  void didChangeAppLifecycleState(AppLifecycleState state) {
    if (state == AppLifecycleState.inactive && !widget.uerGallery) {
      logI("take picture screen inactive");
      var getXController = Get.find<TakePictureScreenController>();
      getXController.cameraController.dispose();
    } else if (state == AppLifecycleState.resumed && !widget.uerGallery) {
      logI("take picture screen resumed");
      var getXController = Get.find<TakePictureScreenController>();
      getXController.resumedKey.value = !getXController.resumedKey.value;
    }
  }

  Future<void> _initCamera(TakePictureScreenController getXController,
      bool isRearCamera, bool isWidgetActive) async {
    if (widget.uerGallery) {
      getXController.pickPicture().whenComplete(() => Get.back());
      return;
    }
    await getXController.initImage();
  }

  @override
  Widget build(BuildContext context) {
    return GetBuilder<TakePictureScreenController>(
        init: Get.put(
          TakePictureScreenController(
              imagePathList: widget.imagePathList,
              photoPathCallBack: widget.photoPathCallBack,isUserGalleryOnly: widget.uerGallery),
        ),
        builder: (getXController) => Scaffold(
              appBar: AppBar(
                leading: IconButton(
                  alignment: Alignment.centerRight,
                  icon: Icon(
                    Icons.arrow_back_ios_new_outlined,
                    color: Colors.white,
                    size: 36.w,
                  ),
                  padding: EdgeInsets.only(top: 4.h),
                  onPressed: () => Get.back(),
                ),
                leadingWidth: 70.w,
                toolbarHeight: 88.h,
                backgroundColor: Colors.black,
              ),
              body: Obx(() => FutureBuilder<void>(
                    future: _initCamera(
                        getXController,
                        getXController.isRearCamera.value,
                        getXController.resumedKey.value),
                    builder: (context, snapshot) {
                      if (widget.uerGallery) {
                        return Container();
                      } else {
                        if (snapshot.connectionState == ConnectionState.done) {
                          return Column(
                            children: [
                              SizedBox(
                                width: 1.sw,
                                height: 1050.h,
                                child: CameraPreview(
                                    getXController.cameraController),
                              ),
                              Expanded(
                                child: Container(
                                  alignment: Alignment.center,
                                  decoration:
                                      const BoxDecoration(color: Colors.black),
                                  padding: EdgeInsets.only(
                                      top: 32.h, left: 40.w, right: 40.w),
                                  child: Column(
                                    children: [
                                      Text("请将正脸对准画面中央",
                                          style: TextStyle(
                                              fontSize: 28.sp,
                                              color: Colors.white)),
                                      SizedBox(height: 64.h),
                                      Flex(
                                        direction: Axis.horizontal,
                                        children: [
                                          _buildGalleryWidget(getXController),
                                          _buildTakePictureWidget(
                                              getXController),
                                          _buildReserveCameraWidget(
                                              getXController)
                                        ],
                                      ),
                                    ],
                                  ),
                                ),
                              )
                            ],
                          );
                        } else {
                          return const Center(
                              child: CircularProgressIndicator());
                        }
                      }
                    },
                  )),
            ));
  }

  Widget _buildGalleryWidget(TakePictureScreenController controller) {
    return Expanded(
        flex: 15,
        child: InkWell(
          child: Container(
            height: 96.w,
            width: 96.w,
            decoration: BoxDecoration(
                image: DecorationImage(
                    fit: BoxFit.fill,
                    image: DeviceImage(controller.latestImage)),
                color: Colors.white,
                borderRadius: BorderRadius.circular(10.w)),
          ),
          onTap: () => controller.pickPicture(),
        ));
  }

  Widget _buildTakePictureWidget(TakePictureScreenController getXController) {
    return Expanded(
        flex: 70,
        child: InkWell(
          child: Image(
              width: 140.w,
              height: 140.w,
              image:
                  const AssetImage("assets/images/public_take_photo_icon.png")),
          onTap: () =>
              getXController.takePicture(getXController.cameraController),
        ));
  }

  Widget _buildReserveCameraWidget(TakePictureScreenController controller) {
    return Expanded(
        flex: 15,
        child: InkWell(
          child: Image(
            width: 96.w,
            height: 96.w,
            image: const AssetImage(
                "assets/images/public_reserve_camera_icon.png"),
          ),
          onTap: () => controller.changeIsRearCamera(),
        ));
  }
}

//图片展示
class DisplayPictureScreen extends StatelessWidget {
  final String imagePath;
  final bool isShowRetake;
  final TakePictureScreenController? takePictureScreenController;

  const DisplayPictureScreen({
    super.key,
    required this.imagePath,
    this.isShowRetake = true,
    this.takePictureScreenController,
  });

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        leading: IconButton(
          alignment: Alignment.centerRight,
          icon: Icon(
            Icons.arrow_back_ios_new_outlined,
            color: Colors.white,
            size: 36.w,
          ),
          padding: EdgeInsets.only(top: 4.h),
          onPressed: () => Get.back(),
        ),
        leadingWidth: 70.w,
        toolbarHeight: 88.h,
        backgroundColor: Colors.black,
        actions: [
          Visibility(
            visible: isShowRetake,
            child: InkWell(
              child: Container(
                padding: EdgeInsets.only(right: 32.w),
                alignment: Alignment.center,
                child: Text(
                  "重拍",
                  style: TextStyle(
                      fontSize: 32.sp, color: const Color(0xFF1774E0)),
                ),
              ),
              onTap: () => takePictureScreenController?.remakePhoto(imagePath),
            ),
          )
        ],
      ),
      body: Container(
        decoration: const BoxDecoration(color: Colors.black),
        child: Column(
          children: [
            SizedBox(
              height: 1050.h,
              width: 1.sw,
              child: imagePath.startsWith("http")
                  ? Image.network(
                      imagePath,
                      fit: BoxFit.fill,
                    )
                  : Image.file(
                      File(imagePath),
                      fit: BoxFit.fill,
                    ),
            ),
            Visibility(
              visible: isShowRetake,
              child: Container(
                  padding: EdgeInsets.only(top: 158.h),
                  child: CustomButton(
                    text: '上传',
                    width: 420.w,
                    height: 90.h,
                    isAsh: false,
                    onPressed: () =>
                        takePictureScreenController?.uploadImage(imagePath),
                  )),
            )
          ],
        ),
      ),
    );
  }
}
